package com.ming_za.od_updater_sdk.handler;

import com.ming_za.od_updater_sdk.ODUpdater;
import com.ming_za.od_updater_sdk.event.*;
import com.ming_za.od_updater_sdk.exception.UnConnectServerException;
import com.ming_za.od_updater_sdk.obj.ReqValue;
import com.ming_za.od_updater_sdk.processing.record.IUpdateRecorder;
import com.ming_za.od_updater_sdk.server_api.ServerAPIState;
import com.ming_za.od_updater_sdk.utils.VersionUtils;

/**
 * 默认更新监听器
 */
public class DefaultUpdaterHandler implements IUpdateHandler {

    private IUpdateRecorder updateRecorder = null;
    private ODUpdater odUpdater = null;

    private int unpublishedVersion = 0;

    @Override
    public void updateStart(UpdateStartEvent event, ODUpdater odUpdater) {
        this.updateRecorder = odUpdater.getUpdateRecorder();
        this.odUpdater = odUpdater;

        ReqValue<Integer> uv = odUpdater.getUpdaterServerAPI().getUnpublishedVersion(odUpdater.getUnpublishKey(), odUpdater);
        if (uv.getServerAPIState() != ServerAPIState.SUCCESS){
            throw new UnConnectServerException("密钥错误");
        }
        unpublishedVersion = uv.getValue();
        odUpdater.getLogger().debug("内测版本--->[v" + VersionUtils.intToVersion(unpublishedVersion) + "]");
    }

    private int nowVersion = 0;

    @Override
    public void updateStartVersion(int version) {
        nowVersion = version;
        if (unpublishedVersion != version) {
            updateRecorder.useVersion(odUpdater, version);
        }
    }

    @Override
    public void preUpdate(PreUpdateEvent event) {
    }

    @Override
    public void update(UpdatingEvent event) {

    }

    @Override
    public void postUpdate(PostUpdateEvent event) {
        if (unpublishedVersion != nowVersion) {
            updateRecorder.addRes(event.getRes().getId());
        }
    }

    @Override
    public void updateError(UpdateErrorEvent event) {

    }

    @Override
    public void updateDoneVersion(int version) {
        if (unpublishedVersion != nowVersion) {
            updateRecorder.complete();
        }
    }

    @Override
    public void allUpdateComplete(UpdateCompleteEvent event) {
        //出现异常则切断记录器
        if (event.hasError() && unpublishedVersion != nowVersion){
            updateRecorder.closeStream();
        }
    }
}
